<?php

require_once 'requires.php';

session_start();

$command = GetCommand();
$data = array();

if ($command == 'cleanup') {
    $db = DBUtils::Create();
    $db->cleanup();
    print_r("Cleaned");
    die;
}

$login = GateWay::CheckLogin();

if (!$login) {
    header("Location: login.php");
    die;
}

if (!$command) {
    header("Location: lobby.html");
    die;
}

try {
    if ($command != null) {
        if ($command == 'login') {
            $res = call_user_func("Gateway::" . $command);
            if ($res == 'lobby') {
                header("Location: lobby.html");
            } else if ($res == 'ingame') {
                header("Location: ingame.html");
            } else {
                header("Location: login.php");
            }
            die;
        } else if ($command == 'exitgame') {
            call_user_func("Gateway::" . $command);
            header("Location: lobby.html");
            die;
        } else if ($command == "loadgame") {
            call_user_func("Gateway::" . $command);
            header("Location: ingame.html");
            die;
        } else if ($command == 'logout') {
            call_user_func("Gateway::" . $command);
            header("Location: login.php");
            die;
        } else if ($command == 'addUser') {
            $res = call_user_func("Gateway::" . $command);
            if ($res) {
                header("Location: login.php");
            } else {
                header("Location: addUser.php");
            }
            die;
        } else if ($command == 'changePass') {
            $res = call_user_func("Gateway::" . $command);
            if ($res) {
                header("Location: login.php");
            } else {
                header("Location: changePassword.php");
            }
            die;
        } else if (method_exists("Gateway", $command)) {
            #$time_start = microtime_float();
            $result = call_user_func("Gateway::" . $command);
            #$time_end = microtime_float();
            #DEBUG($command .": ".($time_end - $time_start));
            echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
            
        } else {
            echo "Unknown command: $command";
            die;
        }
    }
} catch (Exception $ex) {
    print_r($ex->getMessage());
    print_r($ex->getTrace());
    throw $ex;
}


function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

?>